/**
 * @author David Young
 */
package csab.core.utility;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.Log;

import csab.core.Sprite;
/**
 * Generates Sprites based on the parameters of the
 * constructor.
 * @author David Young
 */
public class SpriteFactory {
	private boolean canDie;
	private int health;
	private String name;
	private Class<?> obj;
	private String type;
	/**
	 * This is the constructor for this SpriteFactory object.
	 * These parameters specify the type and attributes of Sprites
	 * generated from this object.
	 * @param health The initial and maximum health of a new Sprite.
	 * @param canDie Whether or not a new Sprite is capable of
	 * being killed.
	 * @param name The name of the new Sprite.
	 * @param type The type of Sprite to create. Must be a class within 
	 * the csab.game.sprites package.
	 * @throws ClassNotFoundException
	 * @see csab.core.Sprite
	 */
	public SpriteFactory(int health, boolean canDie, String name, String type) throws ClassNotFoundException
	{
		this.type = type;
		this.name = name;
		try {
			obj = Class.forName("csab.game.sprites."+type);
		} catch (ClassNotFoundException e) {
			Log.error("Type :: " + type + " not found!");
			throw e;
		}
	}
	
	/**
	 * Generate a new Sprite based on the parameters
	 * specified to the constructor.
	 * @return A new Sprite.
	 * @throws SlickException
	 * @see csab.core.Sprite
	 */
	public Sprite createNewSprite() throws SlickException
	{
		Sprite newobj = null;
		try {
			newobj = (Sprite)obj.newInstance();
		} catch (InstantiationException e) {
			Log.error("Class could not be instantiated!");
			throw new SlickException("Class could not be instantiated!");
		} catch (IllegalAccessException e) {
			Log.error("Type :: " + type + " cannot be accessed!");
			throw new SlickException("Type :: " + type + " cannot be accessed!");
		} catch (ClassCastException e)
		{
			Log.error("Type :: " + type + " is not a subclass of Sprite!");
			throw new SlickException("Type :: " + type + " is not a subclass of Sprite!");
		}
		
		newobj.setName(name);
		newobj.setCanDie(canDie);
		newobj.setMaxHealth(health);
		newobj.giveHealth(health);
		newobj.setDrawable(true);
		newobj.setCanCollide(true);
		return newobj;
	}
}
